package ppa.marc.importer.database;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;

import ppa.marc.domain.Field;
import ppa.marc.domain.SubField;
import ppa.marc.importer.data.DataIntegrityException;

public class JdbcFieldInserter implements FieldInserter {
	private static final String SELECT_ID_SQL = "select id from marc_field where record_id=? and position=?";
	private final JdbcTemplate jdbcTemplate;
	private final SubFieldInserter subFieldInserter;

	public JdbcFieldInserter(JdbcTemplate jdbcTemplate, SubFieldInserter subFieldInserter) {
		this.jdbcTemplate = jdbcTemplate;
		this.subFieldInserter = subFieldInserter;
	}

	@Override
	public long insertField(Field field, long recordId, int position) throws DataIntegrityException, DataInsertionException {
		long id = -1;
		try {
			insertToDatabase(field, recordId, position);
			id = jdbcTemplate.queryForInt(SELECT_ID_SQL, recordId, position);
			int subFieldPosition = 0;
			for(SubField subField : field.getSubFields()) {
				subFieldInserter.insert(subField, subFieldPosition++, id);
			}
		} catch(DataIntegrityViolationException missingRecord) {
			throw new DataIntegrityException("Parent record with internal identifier " + recordId + " doesn't exist.");
		}
		return id;
	}

	private void insertToDatabase(Field field, long recordId, int position) {
		if(field.isControlField()) {
			jdbcTemplate.update("insert into marc_field (marc_id, position, record_id) values (?, ?, ?)", field.getId(), position, recordId);
		}
		else {
			jdbcTemplate.update("insert into marc_field (marc_id, position, record_id, indicator_1, indicator_2) values (?, ?, ?, ?, ?)", field.getId(), position, recordId, field.getFirstIndicator(), field.getSecondIndicator());
		}
	}
}
